package n50_atomic;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fu
 * @date 2022-02-03 13:47
 * 概要：
 * ---------------------------------------------------------------
 * |                                                             |
 * |           原子整数API AtomicInteger 的 方法                   |
 * |                                                             |
 * |==============================================================
 */
public class T1_AtomicInteger加减 {

    public static void main(String[] args) {

        AtomicInteger i = new AtomicInteger(0);

        // 自增 并 获取   ++i
        System.out.println(i.incrementAndGet());   // 1

        // 获取 并 自增   i++
        System.out.println(i.getAndIncrement());   // 1

        // 获取值 get
        System.out.println("i.get() = " + i.get()); // 2

        // --i
        System.out.println(i.decrementAndGet()); // 1
        // i--
        System.out.println(i.getAndDecrement()); // 1

        System.out.println("i.get() == " + i.get()); // 0

        // 获取 并 +指定值
        System.out.println(i.getAndAdd(5)); // 0

        // +指定值 并 获取
        System.out.println(i.addAndGet(5)); // 10

        System.out.println("i.get() === " + i.get()); // 10

    }

}


// ---------------------- 自由测试，非正篇内容 -------------- 可删除 -----------------
@Slf4j
class Test{
     static final AtomicInteger i = new AtomicInteger(0);
     static final BlockingQueue<Integer> msgQueue = new LinkedBlockingQueue<>();

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        Thread t2 = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                while (true){

                    int i = increment();
                    msgQueue.add(i);
                    System.out.println("add-------" + i);
                }
            }
        }, "t2");
        t2.start();


        while (true){
            Thread.sleep(400);
            Integer take = msgQueue.take();
            if(take%5==0){

                System.out.println("--------被5整除---------"+take);
            }
        }


    }

    public static int increment() throws ExecutionException, InterruptedException {

        final FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws InterruptedException {
                Thread.sleep(200);
                return i.incrementAndGet();
            }
        });
        new Thread(task, "T1").start();
        return  task.get();

    }

















}